package concurrency;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class WaitPerson implements Runnable {
    private static int sCounter = 0;

    private final int mId = sCounter++;

    private final Restaurant mRestaurant;

    /* package */ BlockingQueue<Plate> mFilledOrders = new LinkedBlockingQueue<Plate>();

    public WaitPerson(Restaurant rest) {
        mRestaurant = rest;
    }

    public void placeOrder(Customer customer, Food food) {
        try {
            // Shouldn't actually block because this is
            // a LinkedBlockingQueue with no size limit:
            mRestaurant.mOrders.put(new Order(customer, this, food));
        } catch (InterruptedException e) {
            System.out.println(this + " placeOrder interrupted");
            // e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                Plate plate = mFilledOrders.take();
                Order order = plate.getOrder();
                Customer customer = order.getCustomer();
                System.out.println(this + "received " + plate
                                   + " delivering to " + customer);
                customer.deliver(plate);
            }
        } catch (InterruptedException e) {
            System.out.println(this + " interrupted");
        }
        // 下班，不在值班
        System.out.println(this + " off duty");
    }

    @Override
    public String toString() {
        return "WaitPerson_" + mId + " ";
    }
}
